package com.customization.unionpay.market.workflowaction;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.MPManagePlatformUtils;
import com.customization.unionpay.contract.serivce.impl.ContractBaseServiceImpl;
import com.customization.unionpay.market.util.DailyReportRelated;
import com.customization.unionpay.market.util.PropUtils;
import weaver.conn.RecordSetTrans;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author sjm
 * @description 营销事项申请表单节点(归档)action
 */
public class MarketingApplicationEndAction implements Action {

    private static final Logger log = LoggerFactory.getLogger(MarketingApplicationEndAction.class);

    @Override
    public String execute(RequestInfo requestInfo) {


        RequestManager rm = requestInfo.getRequestManager();

        try {
            ContractBaseServiceImpl contractBaseService = new ContractBaseServiceImpl();

            // 流程表单id
            int formId = rm.getFormid();

            Map<String, Object> allFormData = com.customization.unionpay.market.util.FormDataUtils.getAllFormData(requestInfo);

            Map<String, String> mainMap = (Map<String, String>) allFormData.get("mainMap");
            // 所有明细表的值
            Map<String, Map<String, Map<String, String>>> detailMap = (Map<String, Map<String, Map<String, String>>>) allFormData.get("detailMap");

            String bdh = mainMap.get("bdh");
            log.info("bdh:" + bdh);
            // 内部资金合计
            String nbczjehjStr = mainMap.get("nbczjehj");
            log.info("nbczjehjStr:" + nbczjehjStr);
            // 合同编号
            String htbh = mainMap.get("htbhwb");
            log.info("htbh:" + htbh);
            Double nbczjehj = Double.parseDouble(nbczjehjStr);

            // 营销活动事项台账表单id
            int marketingActivityLedgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));
            // 获取营销活动日报表台账主表表名
            String marketingActivityLedgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(marketingActivityLedgerFormId);
            log.info("marketingActivityLedgerTableName:" + marketingActivityLedgerTableName);
            // 资金来源
            String fundSourceValue = mainMap.get("zjly");
            if (StrUtil.isNotBlank(fundSourceValue)) {
                // 营销平台活动授权码
                String authCode = mainMap.get("yxpthdsqm");
                if (StrUtil.isNotBlank(authCode)) {
                    // [资金来源]=内外部联合营销，触发判断是否异常转正操作
                    String selectValueFundSource = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "zjly", "内外部联合营销");
                    log.info("zjlyEnumNWValue:" + selectValueFundSource);
                    if (StrUtil.isNotBlank(selectValueFundSource)) {
                        if (fundSourceValue.equals(selectValueFundSource)) {
                            // 营销活动日报表台账表单id
                            int reportFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_daily_report_form_id"));
                            String selectValuerRblslxError = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "异常数据");
                            log.info("selectValuerRblslxError:" + selectValuerRblslxError);
                            String selectValuerRblslxNormal = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "正常数据");
                            log.info("selectValuerRblslxNormal:" + selectValuerRblslxNormal);
                            // 营销活动日报表台账资金来源
                            String selectValueFundSourceRB = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "zjly", "内外部联合营销");
                            log.info("selectValueFundSourceRB:" + selectValueFundSourceRB);
                            // 获取营销活动日报表台账主表表名
                            String reportFormTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(reportFormId);
                            log.info("reportFormTableName:" + reportFormTableName);
                            // 根据SQ申请单的【营销平台活动授权码】去查询【营销活动日报表台账】是否有对应【营销平台活动授权码】数据， 若【营销日报表台账】存在对应授权码流水数据，则校验该条数据是否有【营销平台事项申请单号】数据
                            // 内部出资金额
                            List<JSONObject> results = DailyReportRelated.selectInfoByAuthCode(authCode, selectValuerRblslxError, selectValuerRblslxNormal, selectValueFundSourceRB, reportFormTableName);
                            if (results.size() > 0) {
                                // ① 若返回【营销平台事项申请单号】为空值，且【日报流水类型】=异常数据， 则自动更新日报数据字段【日报流水类型】为“正常数据”，系统根据申请单内部出资金额合计可以清算金额累减（不够也行，不能小于零）更新为“正常数据”，不符合的更新为“异常数据”
                                Double allM = nbczjehj;
                                for (JSONObject result : results) {
                                    String id = result.getString("id");
                                    String qsje = result.getString("qsje");
                                    String yxptCode = result.getString("yxptsxsqdh");
                                    if (yxptCode == null || "".equals(yxptCode)) {
                                        if (allM > 0) {
                                            if (qsje != null && !"".equals(qsje)) {
                                                Double qsjeDb = Double.valueOf(qsje);
                                                DailyReportRelated.updateRblslx(id, selectValuerRblslxNormal, reportFormTableName);
                                                allM = allM-qsjeDb;
                                            } else {
                                                log.error("日报表清算金额异常：id=" + id + ",qsje=" + qsje);
                                            }
                                        }
                                    }
                                }
                                // 写入单号
                                DailyReportRelated.updateBdh(authCode, bdh, selectValueFundSourceRB, reportFormTableName);

                            } else {
                                // 没有对应授权码流水数据！
                                log.error("no mapping sqmData");
                            }
                        } else {
                            // 该流程资金来源不是内外部联合营销！
                            log.error("this zjly is not nwbyx");
                        }

                        String htbhNew = htbh;
                        // 归档时，[内部出资金额]写入合同明细行[已付款(含SQ 申请)金额]和[内部出资累计金额]，扣减[审批中金额]扣减 1 提交 2 回退 3 归档 4、本次调整金额
                        String[] singleHtbhs = htbh.split(",");
                        log.info("htCodeLength："+singleHtbhs.length);
                        if(singleHtbhs.length == 1){
                            Map<String, Map<String, String>> dt1 = detailMap.get("dt1");
                            for (String key : dt1.keySet()) {
                                Map<String, String> value = dt1.get(key);
                                // 内部出资金额
                                String nbczje = value.get("nbczje");
                                // 履约明细号
                                Integer lymxh = Integer.valueOf(value.get("lymxh"));
                                log.info("lymxh:" + lymxh);
                                contractBaseService.updateAmountFunded(3, lymxh, nbczje);
                            }
                        }else if(singleHtbhs.length > 1) {
                            // 虚拟合同可能在本地生成
                            try {
                                // 供应商名称
                                List<String> gysmcList = new ArrayList<>();
                                String gysmc = mainMap.get("yxgys");
                                gysmcList.add(gysmc);
                                log.info("gysmcList："+gysmcList);

                                String act_nm = mainMap.get("act_nm");
                                log.info("act_nm："+act_nm);
                                // 活动管理人
                                // Integer hdglr = Integer.parseInt(mainMap.get("hdglr"));

                                List<String> list = new ArrayList<>(Arrays.asList(singleHtbhs));
                                log.info("list："+list);

                                String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                                Integer sqr = Integer.valueOf(mainMap.get("sqr"));
                                log.info("sqr："+sqr);
                                htbhNew = mainMap.get("gxhtbh");
                                log.info("htbhNew："+htbhNew);
                                String htId = contractBaseService.marketingAdd(sqr, date, act_nm, htbhNew, nbczjehjStr, list, gysmcList);
                                log.info("htId："+htId);
                                changeDataThread(marketingActivityLedgerTableName,authCode,htId);
                            }catch (Exception e){
                                log.error("生成共享合同异常："+e.getMessage());
                                requestInfo.getRequestManager().setMessageid("10001");
                                requestInfo.getRequestManager().setMessagecontent("生成共享合同异常："+e.getMessage());
                                return Action.FAILURE_AND_CONTINUE;
                            }
                        }
                        // 判斷是否是营销项目管理平台发起了
                        // 来源系统
                        String lyxt = mainMap.get("lyxt");
                        log.info("lyxt："+lyxt);
                        if(lyxt != null && !"".equals(lyxt)){
                            String projectCode = mainMap.get("project_code");
                            String yxptlsh = mainMap.get("yxptlsh");
                            //        String projectCode = FormDataUtils.getProductInfo(project_code).getString("code");
                            String nbczjehjToWanYuan = FormDataUtils.changeYuanToWanYuan(nbczjehjStr);
                            log.info("nbczjehjToWanYuan:"+nbczjehjToWanYuan);
                            // 审批结果
                            String auditMessage = "审核通过";
                            // 更新项目管理平台
                            String result = MPManagePlatformUtils.applicationProcessPush(yxptlsh, authCode, projectCode, htbhNew, nbczjehjToWanYuan, auditMessage);
                            log.info("yxxmglptResult："+result);

                            JSONObject resultJson = JSONObject.parseObject(result);

                            String code = resultJson.getString("code");

                            if (!"200".equals(code)) {
                                String message = resultJson.getString("message");
                                log.error("request error：" + message);
                                requestInfo.getRequestManager().setMessageid("10001");
                                requestInfo.getRequestManager().setMessagecontent("营销平台活动授权码："+authCode+"相关信息，推送营销项目管理平台申请金额失败："+message);
                                return Action.FAILURE_AND_CONTINUE;
                            }
                        }else {
                            log.info("当前申请单不是营销项目管理平台发起，不需要推送营销项目管理平台！");
                        }
                    } else {
                        requestInfo.getRequestManager().setMessageid("10001");
                        requestInfo.getRequestManager().setMessagecontent("资金来源枚举异常！");
                        return Action.FAILURE_AND_CONTINUE;
                    }
                } else {
                    requestInfo.getRequestManager().setMessageid("10001");
                    requestInfo.getRequestManager().setMessagecontent("营销平台活动授权码不能为空！");
                    return Action.FAILURE_AND_CONTINUE;
                }
            } else {
                requestInfo.getRequestManager().setMessageid("10001");
                requestInfo.getRequestManager().setMessagecontent("资金来源不能为空！");
                return Action.FAILURE_AND_CONTINUE;
            }

        } catch (Exception e) {
            log.error("all application end error：" + e.getMessage());
            // 异常报错是填写异常信息，阻止流程继续流转
            requestInfo.getRequestManager().setMessageid("10001");
            requestInfo.getRequestManager().setMessagecontent(e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    /**
     * 修改活动事项申请的合同编号
     * @param tableName
     * @param yxpthdsqm
     * @param htId
     */
    public void changeDataThread(String tableName,String yxpthdsqm,String htId){
        try {
            Thread t = new Thread(new Runnable(){
                public void run(){
                    try {
                        String sleepTime = PropUtils.BB_LOG.getPropValue("marketSubject", "sleepTime");
                        log.info("sleepTime:"+sleepTime);
                        Thread.sleep(Long.valueOf(sleepTime));
                        RecordSetTrans rst = new RecordSetTrans();
                        // 开启事务（关闭自动提交）
                        rst.setAutoCommit(false);
                        try {
                            String updateSql = "update #{tableName} set htbh=?  where yxpthdsqm = ? ";
                            updateSql = updateSql.replace("#{tableName}",tableName);
                            log.info("updateSql:"+updateSql);
                            rst.executeUpdate(updateSql,htId,yxpthdsqm);
                            // 提交事务
                            rst.commit();
                        } catch (Exception e) {
                            // 回滚
                            rst.rollback();
                            log.info("修改数据错误:"+e.getMessage());
                        }
                    } catch (Exception e) {
                        log.info("延迟报错:"+e.getMessage());
                    }
                }});
            t.start();
        }catch (Exception e){
            log.info("回传异常，原因："+e.getMessage());
        }
    }

}
